/**
 * Mermaid语法映射类型定义
 * 专利协作写作平台 - 图形化拖拽功能模块
 */

// 主配置接口
export interface MermaidSyntaxMapping {
  version: string
  mermaidVersion: string
  lastUpdated: string
  description: string
  supportedChartTypes: string[]
  supportedCharts: ChartTypeMapping[]  // 添加这个字段
  phaseMapping: PhaseMapping
  globalSettings: GlobalSettings
  conversionRules: ConversionRules
  changelog: ChangelogEntry[]
}

// Phase映射
export interface PhaseMapping {
  phase1: string[]
  phase2: string[]
  phase3: string[]
}

// 全局设置
export interface GlobalSettings {
  patentDocumentCompliant: boolean
  colorRestrictions: ColorRestrictions
  fontRestrictions: FontRestrictions
  exportSettings: ExportSettings
}

export interface ColorRestrictions {
  allowCustomColors: boolean
  enforceBlackAndWhite: boolean
  background: string
  foreground: string
}

export interface FontRestrictions {
  allowCustomFonts: boolean
  standardFont: string
}

export interface ExportSettings {
  defaultDPI: number
  supportedFormats: string[]
  A4Optimization: boolean
}

// 转换规则
export interface ConversionRules {
  autoFallback: boolean
  preserveOriginalCode: boolean
  warnOnConversion: boolean
}

// 更新日志
export interface ChangelogEntry {
  version: string
  date: string
  changes: string[]
}

// 图表类型映射
export interface ChartTypeMapping {
  type: ChartType
  aliases?: string[]
  phase: 1 | 2 | 3
  supported: boolean
  description: string
  directions?: DirectionMapping[]
  nodes: NodeTypeMapping[]
  connections: ConnectionTypeMapping[]
  specialSyntax?: SpecialSyntaxMapping[]
  warnings?: WarningMapping[]
  limitations?: LimitationMapping[]
  conversionRules?: ChartConversionRules
}

export type ChartType = 'flowchart' | 'stateDiagram' | 'sequenceDiagram' | 'classDiagram' | 'erDiagram' | 'pie'

// 方向映射
export interface DirectionMapping {
  code: string
  alias?: string
  description: string
  label: string
  supported: boolean
}

// 节点类型映射
export interface NodeTypeMapping {
  type: string
  name: string
  syntax: string[]
  syntax_export: string[]
  examples: string[]
  visualComponent: string
  supportLevel: SupportLevel
  description: string
  properties: NodeProperties
  useCases: string[]
  fallback?: FallbackMapping
}

export type SupportLevel = 'full' | 'partial' | 'none'

export interface NodeProperties {
  width: DimensionRange
  height: DimensionRange
  textAlign: string
  borderRadius?: string | number
  strokeWidth: number
  doubleBorder?: boolean
}

export interface DimensionRange {
  min: number
  max: number
  default: number
}

export interface FallbackMapping {
  type: string
  reason: string
  visualDifference: boolean
  conversionNote?: string
}

// 连接类型映射
export interface ConnectionTypeMapping {
  type: string
  name: string
  syntax: string[]
  syntax_export: string[]
  examples: string[]
  visualComponent: string
  supportLevel: SupportLevel
  description: string
  properties: ConnectionProperties
  useCases: string[]
  hasLabel: boolean
}

export interface ConnectionProperties {
  arrowType: string
  lineStyle: string
  strokeWidth: number
  color: string
  labelSupported: boolean
  dashArray?: string
}

// 特殊语法映射
export interface SpecialSyntaxMapping {
  feature: string
  name: string
  supported: boolean
  phase?: number
  examples: SyntaxExample[]
  note?: string
  reason?: string
}

export interface SyntaxExample {
  type: string
  syntax: string
  description: string
  note?: string
}

// 警告映射
export interface WarningMapping {
  type: string
  description: string
  keywords?: string[]
  characters?: string[]
  context?: string
  solution: string
}

// 限制映射
export interface LimitationMapping {
  feature: string
  description: string
  status: string
  phase?: number
  reason: string
}

// 图表级转换规则
export interface ChartConversionRules {
  nodeShapeFallback: Record<string, string>
  connectionStyleFallback: Record<string, string>
  textProcessing: TextProcessingRules
}

export interface TextProcessingRules {
  stripHTML: boolean
  preserveUnicode: boolean
  maxLength: number
}

// 转换规则配置
export interface ConversionRulesConfig {
  version: string
  description: string
  lastUpdated: string
  fallbackStrategies: FallbackStrategies
  conversionPriority: ConversionPriority
  preservationRules: PreservationRules
  compatibilityLevels: CompatibilityLevels
  userNotificationTemplates: UserNotificationTemplates
  autoFixRules: AutoFixRules
  validationRules: ValidationRules
  performanceOptimization: PerformanceOptimization
}

export interface FallbackStrategies {
  nodeShapes: Record<string, FallbackStrategy>
  connectionStyles: Record<string, FallbackStrategy>
  specialFeatures: Record<string, SpecialFeatureStrategy>
}

export interface FallbackStrategy {
  fallbackTo: string
  reason: string
  visualDifference: boolean
  userNotification: boolean
}

export interface SpecialFeatureStrategy {
  action: 'remove' | 'convert'
  convertTo?: string
  reason: string
  preserveInCode: boolean
  userNotification: boolean
}

export interface ConversionPriority {
  high: string[]
  medium: string[]
  low: string[]
}

export interface PreservationRules {
  originalCode: PreservationRule
  conversionLog: PreservationRule
  userModifications: PreservationRule
}

export interface PreservationRule {
  preserve: boolean
  location?: string
  includeTimestamp?: boolean
  includeUserActions?: boolean
  trackChanges?: boolean
  purpose: string
}

export interface CompatibilityLevels {
  full: CompatibilityLevel
  high: CompatibilityLevel
  medium: CompatibilityLevel
  low: CompatibilityLevel
  none: CompatibilityLevel
}

export interface CompatibilityLevel {
  score: number
  description: string
  action: string
  userPrompt: boolean
  promptType?: 'info' | 'warning' | 'error'
}

export interface UserNotificationTemplates {
  [key: string]: NotificationTemplate
}

export interface NotificationTemplate {
  title: string
  message: string
  details: string
  severity: 'info' | 'warning' | 'error'
  showPreview?: boolean
  showAlternatives?: boolean
  showSupportedTypes?: boolean
  autoFixAvailable?: boolean
}

export interface AutoFixRules {
  [key: string]: AutoFixRule
}

export interface AutoFixRule {
  enabled: boolean
  pattern?: string
  patterns?: AutoFixPattern[]
  replacement?: string
  maxLength?: number
  action?: string
  suffix?: string
  description: string
}

export interface AutoFixPattern {
  pattern: string
  replacement: string
  description: string
}

export interface ValidationRules {
  [key: string]: ValidationRule
}

export interface ValidationRule {
  pattern?: string
  validPatterns?: string[]
  maxLength?: number
  allowedCharacters?: string
  prohibitedTags?: string[]
  errorMessage: string
}

export interface PerformanceOptimization {
  maxNodes: number
  maxConnections: number
  complexityThreshold: number
  recommendations: Record<string, string>
}

// 模板相关类型
export interface FlowchartTemplates {
  version: string
  description: string
  lastUpdated: string
  categories: TemplateCategory[]
  quickStart: QuickStartTemplate[]
  patentSpecific: PatentSpecificTemplate[]
  metadata: TemplateMetadata
}

export interface TemplateCategory {
  id: string
  name: string
  description: string
  icon: string
  templates: Template[]
}

export interface Template {
  id: string
  name: string
  description: string
  complexity: 'simple' | 'medium' | 'complex'
  nodes: number
  connections: number
  code: string
  preview: string
  useCases: string[]
}

export interface QuickStartTemplate {
  id: string
  name: string
  description: string
  code: string
  nodes: number
  connections: number
}

export interface PatentSpecificTemplate {
  id: string
  name: string
  description: string
  code: string
  nodes: number
  connections: number
  useCases: string[]
}

export interface TemplateMetadata {
  totalTemplates: number
  complexity: Record<string, number>
  usage: {
    mostUsed: string[]
    recommended: string[]
  }
  updates: {
    lastTemplateAdded: string
    plannedUpdates: string[]
  }
}

// 解析和生成相关接口
export interface ParseResult {
  chartHeader?: ChartHeader
  chartType: ChartType | 'unknown'
  ast: AST
  compatibility: CompatibilityReport
  nodes: ParsedNode[]
  connections: ParsedConnection[]
}

export interface AST {
  type: string
  chartType: ChartType
  nodes: ASTNode[]
  connections: ASTConnection[]
  directives: ASTDirective[]
}

export interface ASTNode {
  id: string
  type: string
  text: string
  properties?: Record<string, any>
}

export interface ASTConnection {
  from: string
  to: string
  type: string
  label?: string
  properties?: Record<string, any>
}

export interface ASTDirective {
  type: string
  value: string
}

export interface CompatibilityReport {
  overall: SupportLevel
  warnings: CompatibilityWarning[]
  errors: CompatibilityError[]
  supportedFeatures: string[]
  unsupportedFeatures: string[]
}

export interface CompatibilityWarning {
  type: string
  message: string
  element?: any
  fallback?: FallbackMapping
}

export interface CompatibilityError {
  type: string
  message: string
  element?: any
}

export interface ParsedNode {
  id: string
  type: string
  text: string
  x?: number
  y?: number
  width?: number
  height?: number
  properties?: Record<string, any>
}

export interface ParsedConnection {
  id: string
  from: string
  to: string
  type: string
  label?: string
  properties?: Record<string, any>
}

export interface ParsedDirective {
  type: string
  value: string
}

// 可视化图表接口
export interface VisualChart {
  type: ChartType
  direction?: string
  nodes: VisualNode[]
  connections: VisualConnection[]
  directives?: VisualDirective[]
  metadata?: ChartMetadata
}

export interface VisualNode {
  id: string
  type: string
  text: string
  x: number
  y: number
  width: number
  height: number
  selected?: boolean
  properties?: Record<string, any>
}

export interface VisualConnection {
  id: string
  from: string
  to: string
  fromPort?: string
  toPort?: string
  type: string
  label?: string
  path?: string
  selected?: boolean
  properties?: Record<string, any>
}

export interface VisualDirective {
  type: string
  value: string
}

export interface ChartMetadata {
  created: string
  modified: string
  version: string
  author?: string
  description?: string
}

// 导入结果接口
export interface ImportResult {
  success: boolean
  warnings: ImportWarning[]
  errors: ImportError[]
  convertedNodes: ConvertedNode[]
  unsupportedFeatures: UnsupportedFeature[]
}

export interface ImportWarning {
  type: 'node_fallback' | 'feature_limitation' | 'syntax_conversion'
  message: string
  originalCode: string
  convertedCode: string
  severity: 'info' | 'warning' | 'error'
}

export interface ImportError {
  type: string
  message: string
  line?: number
  column?: number
  code?: string
}

export interface ConvertedNode {
  originalType: string
  convertedType: string
  reason: string
  visualDifference: boolean
}

export interface UnsupportedFeature {
  feature: string
  reason: string
  phase?: number
  alternative?: string
}

// 导入分析接口
export interface ImportAnalysis {
  chartType: ChartType | 'unknown'
  supportLevel: SupportLevel
  potentialIssues: PotentialIssue[]
  recommendedAction: RecommendedAction
}

export interface PotentialIssue {
  type: string
  severity: 'info' | 'warning' | 'error'
  message: string
  suggestion?: string
}

export interface RecommendedAction {
  action: 'direct_import' | 'convert_with_warning' | 'keep_code_mode' | 'recreate'
  reason: string
  confidence: number
}

// 导入对话框接口
export interface ImportDialog {
  title: string
  content: {
    analysis: ImportAnalysis
    options: ImportOption[]
  }
}

export interface ImportOption {
  label: string
  description: string
  action: string
}

// 保留数据接口
export interface PreservedData {
  originalCode: string
  convertedCode: string
  conversionLog: ConversionStep[]
  userModifications: Modification[]
}

export interface ConversionStep {
  timestamp: string
  type: string
  description: string
  before: any
  after: any
}

export interface Modification {
  timestamp: string
  type: string
  description: string
  element: any
  change: any
}

// 更新信息接口
export interface UpdateInfo {
  hasUpdate: boolean
  currentVersion: string
  latestVersion: string
  updateDetails: UpdateDetails
}

export interface UpdateDetails {
  features: string[]
  fixes: string[]
  breaking: string[]
  downloadUrl?: string
}

// Mermaid节点数据结构（用于编辑器）
export interface MermaidNode {
  id: string
  type: string
  text: string
  properties?: Record<string, any>
}

// Mermaid连接数据结构（用于编辑器）
export interface MermaidConnection {
  from: string
  to: string
  type: string  
  label?: string
  properties?: Record<string, any>
}

// 兼容性问题报告
export interface CompatibilityIssue {
  id: string
  type: 'warning' | 'error' | 'info'
  message: string
  suggestion: string
  nodeId?: string
  connectionId?: string
  severity: 'low' | 'medium' | 'high'
}

// 流程图模板
export interface FlowchartTemplate {
  id: string
  name: string
  description: string
  category: string
  nodes: MermaidNode[]
  connections: MermaidConnection[]
  preview?: string
}

// 代码生成器相关类型定义
export interface StyleConfig {
  nodes?: Record<string, StyleProperties>
  classes?: Record<string, StyleProperties>
  classBindings?: Record<string, string>
}

export interface StyleProperties {
  fill?: string
  stroke?: string
  strokeWidth?: number
  color?: string
  fontSize?: string
  fontWeight?: string
}

export interface TemplateData {
  variables?: Record<string, any>
  nodes?: Array<{ text: string }>
  connections?: Array<{ from: string; to: string; label?: string }>
}

export interface ComplexityAnalysis {
  nodeCount: number
  connectionCount: number
  maxDepth: number
  connectionDensity: number
  complexityScore: number
  complexity: 'low' | 'medium' | 'high'
  recommendations: string[]
}

export type ExportFormat = 'mermaid' | 'markdown' | 'html' | 'json'

export interface CodeDiff {
  additions: string[]
  deletions: string[]
  modifications: string[]
  hasChanges: boolean
}

// 代码生成配置
export interface CodeGenerationOptions {
  direction?: string
  styles?: StyleConfig
  optimize?: boolean
  format?: ExportFormat
  validation?: boolean
  statistics?: boolean
}

// 代码生成结果
export interface CodeGenerationResult {
  code: string
  statistics?: {
    lines: number
    nodes: number
    connections: number
    directives: number
    complexity: 'low' | 'medium' | 'high'
  }
  validation?: {
    isValid: boolean
    errors: string[]
  }
  complexity?: ComplexityAnalysis
  metadata?: {
    generatedAt: string
    generator: string
    options: CodeGenerationOptions
  }
}

// 批量生成结果
export interface BatchGenerationResult {
  results: CodeGenerationResult[]
  summary: {
    total: number
    successful: number
    failed: number
    errors: string[]
  }
}

export interface ChartHeader{
  title: string,
  description: string
}
